package com.learning.service.impl;

import com.learning.constant.MessageConstant;
import com.learning.dto.LoginDTO;
import com.learning.entity.Admin;
import com.learning.exceptiom.AccountNotFoundException;
import com.learning.exceptiom.PasswordErrorException;
import com.learning.mapper.AdminMapper;
import com.learning.service.IAdminService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

/**
 * <p>
 * 管理员表 服务实现类
 * </p>
 *
 * @author itRao
 * @since 2024-05-23
 */
@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements IAdminService {

    @Override
    public Admin login(LoginDTO loginDTO) {
        String username = loginDTO.getUsername();
        String password = loginDTO.getPassword();

        Admin admin = lambdaQuery().eq(Admin::getUsername, username).one();

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (admin == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        password = DigestUtils.md5DigestAsHex(password.getBytes()); //密码进行md5加密后比对
        if (!password.equals(admin.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        return admin;
    }
}
